//
//  DCHttpManager.m
//  Demo
//
//  Created by Kyle on 2022/12/31.
//

#import "DCHttpManager.h"
#import "AFHTTPSessionManager.h"
#import "DCResponseData.h"
#import "DCLoginViewController.h"
#import "DCBaseNavController.h"

@interface DCHttpManager ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation DCHttpManager

+(DCHttpManager *)shareInfo{
    static DCHttpManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        [self configHttps];
    }
    return self;
}

/**
 TODO:配置https证书
 */
- (void) configHttps{
    
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = NO;
    [securityPolicy setValidatesDomainName:YES];
    sessionManager.securityPolicy = securityPolicy;
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"application/xml", @"text/cjson",@"application/json",nil];
    config.timeoutIntervalForResource = 8.0;
    config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    config.URLCache = nil;
    self.manager = sessionManager;
    [self.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    self.manager.requestSerializer.timeoutInterval = 60;
    [self.manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
//    NSMutableDictionary *headers = [NSMutableDictionary dictionary];
//    [headers setValue:@"application/json;text/html;text/json;text/javascript;application/xml;text/cjson" forKey:@"Accept"];
}

/**
 TODO:POST方法
 
 @param url 请求路径
 @param parameters 传参
 @param completeBlock 完成回调
 @return 当前任务
 */
- (NSURLSessionDataTask *)postMessageWithUrl:(NSString *)url parameters:(NSDictionary *)parameters complete:(NSmartCompleteBlock)completeBlock {
    //状态栏网络请求开始旋转
    [self showNewWorkActivity:YES];
    DLog(@"\n接口地址:---%@\n加密前参数:---%@",url,parameters.mj_JSONString);
    [self configureHttpHeader:parameters];
    //处理请求体
    parameters = [self assemblyBodyBy:parameters];
    
    mWeakSelf;
    __block NSURLSessionDataTask *dataTask = [self.manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCResponseData *data = [DCResponseData CreatResponseDataWithDictionary:responseObject];
        if (data.code == -1) {
            data.message = @"【Invalid Session!】";
            [weakSelf dealSpecialCode:data.code];
        }
        
        if (completeBlock) {
            completeBlock(dataTask,data);
        }
       
        //状态栏网络请求结束旋转
        [weakSelf showNewWorkActivity:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DCResponseData *data = [DCResponseData new];
        data.code = 999;
        data.message = @"【Network unavailbale】";
        data.error = error;
        if (completeBlock) {
            // Review:是否会引起循环应用
            completeBlock(dataTask,data);
        }
        //状态栏网络请求结束旋转
        [weakSelf showNewWorkActivity:NO];
    }];
   
    
    return dataTask;
}
- (NSURLSessionDataTask *)postMessageContentImageWithUrl:(NSString *)url parameters:(NSDictionary *)parameters complete:(NSmartCompleteBlock)completeBlock {

    [self showNewWorkActivity:YES];
    NSData *imageData = [parameters objectForKey:@"photo"];
    
    [self configureHttpHeader:parameters];
    parameters = [self assemblyBodyBy:parameters];
    DLog(@"\n接口地址:---%@\n加密前参数:---%@",url,parameters.mj_JSONString);
    
    [self.manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    mWeakSelf;
    __block NSURLSessionDataTask *dataTask =  [self.manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"photo" fileName:@"livePhoto.jpeg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DCResponseData *data = [DCResponseData CreatResponseDataWithDictionary:responseObject];
        if (data.code == -1) {
            data.message = @"【Invalid Session!】";
            [weakSelf dealSpecialCode:data.code];
        }
        
        if (completeBlock) {
            completeBlock(dataTask,data);
        }
        
        //状态栏网络请求结束旋转
        [weakSelf showNewWorkActivity:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DCResponseData *data = [DCResponseData new];
        data.code = 999;
        data.message = @"【Network unavailbale】";
        data.error = error;
        if (completeBlock) {
            // Review:是否会引起循环应用
            completeBlock(dataTask,data);
        }
        //状态栏网络请求结束旋转
        [weakSelf showNewWorkActivity:NO];
    }];
    return dataTask;
}
/**
 TODO:拼接请求体
 
 @param bodyDic 具体接口请求体
 @return 完整请求体
 */
- (NSDictionary *)assemblyBodyBy:(NSDictionary *)bodyDic {
    NSMutableDictionary *mDic  = bodyDic.mutableCopy;
    [mDic removeObjectForKey:@"photo"];
    [mDic removeObjectForKey:@"place_type"];
    return mDic;
}

- (void )configureHttpHeader:(NSDictionary *)body {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    DCUserInfo *userInfo = [[CacheTools sharedCacheTools] getObjForKey:SMARTUSERINFO];
    NSString *x_auth_token =userInfo ?  userInfo.token : @"";
    NSString *x_version = [infoDictionary objectForKey:@"CFBundleVersion"];
    NSString *x_package_name  = [infoDictionary objectForKey:@"CFBundleIdentifier"];;
    NSString *x_app_name =  [infoDictionary objectForKey:@"CFBundleDisplayName"];

    x_package_name = @"com.fintek.ng.market";
    x_app_name = @"daiChao";
    
    [self.manager.requestSerializer setValue:x_auth_token forHTTPHeaderField:@"x-auth-token"];
//    [self.manager.requestSerializer setValue:x_auth_token forHTTPHeaderField:@"loginToken"];

    [self.manager.requestSerializer setValue:x_version forHTTPHeaderField:@"x-version"];
//    [self.manager.requestSerializer setValue:x_version forHTTPHeaderField:@"versionNumber"];

//    [self.manager.requestSerializer setValue:@"ng-loan-market" forHTTPHeaderField:@"x-merchant"];
//    [self.manager.requestSerializer setValue:@"ng-loan-market" forHTTPHeaderField:@"merchantNo"];

    
    [self.manager.requestSerializer setValue:x_package_name forHTTPHeaderField:@"x-package-name"];
    
    [self.manager.requestSerializer setValue:x_app_name forHTTPHeaderField:@"x-app-name"];
    
    [self.manager.requestSerializer setValue:[body objectForKey:@"place_type"] forHTTPHeaderField:@"type"];

//    [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

}

- (void)dealSpecialCode:(NSInteger)code {
    UIWindow *keyWindow = APPDelegate.window;
    DCLoginViewController *loginVC = [[DCLoginViewController alloc] init];
    DCBaseNavController *nav = [[DCBaseNavController alloc] initWithRootViewController:loginVC];
    keyWindow.rootViewController = nav;
}

/**
 TODO:显示网络的运行情况
 
 @param isActivity 是否在请求网络
 */
- (void)showNewWorkActivity:(BOOL)isActivity{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = isActivity;
        
    });
    
}
@end
